package com.easymin.weixin.common.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.controller.v4.ResultTransport;
import com.easymin.weixin.entity.simpleCarPool.WorkCar;
import com.easymin.weixin.entity.simpleCarPool.WorkCarArea;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SimpleCarPoolApi {

  @Value("${module.simpleCarPool.url}")
  private String simpleCarPoolApiGateway;

  @Autowired
  private RestTemplate restTemplate;

  /**
   * 根据经纬度查询路线.
   */
  public static final String ROADLINES =
      "api/workCarArea/roadLines.json?lng={lng}&lat={lat}&appKey={appKey}";
  /**
   * 根据id查询工作车线路.
   */
  public static final String ROADLINE =
      "api/workCarArea/findAreaById/{roadLineId}.json?appKey={appKey}";
  /**
   * 根据id查询单个车辆.
   */
  public static final String CAR = "api/workcar/findWorkCarById/{workCarId}.json?appKey={appKey}";
  /**
   * 查询单个服务人员预约的工作车订单.
   */
  public static final String BOOKS = "api/workCarPickup/books/{employId}.json?appKey={appKey}";
  /**
   * 取消工作车订单.
   */
  public static final String CANCEL = "api/workCarPickup/cancel/{bookId}?appKey={appKey}";
  /**
   * 更新工作车位置.
   */
  public static final String UPDATECAR =
      "api/workcar/update/{workCarId}?address={address}&lat={lat}&lng={lng}&appKey={appKey}";
  /**
   * 下单.
   */
  public static final String BOOK =
      "api/workCarPickup/book.json?roadLineId={roadLineId}&bookLat={bookLat}"
      + "&bookLng={bookLng}&bookTime={bookTime}&bookArea={bookArea}&employId={employId}"
      + "&employName={employName}&employPhone={employPhone}&appKey={appKey}";
  /**
   * V4下单.
   */
  public static final String BOOK_V4 = "api/simplecarpool/v4/book";
  /**
   * V4根据经纬度查询路线.
   */
  public static final String ROADLINES_V4 =
      "api/simplecarpool/v4/roadLines.json?lng={lng}&lat={lat}&appKey={appKey}";
  /**
   * V4查询单条路线.
   */
  public static final String ROADLINE_V4 =
      "api/simplecarpool/v4/findAreaById/{roadLineId}.json?appKey={appKey}";
  /**
   * V4查询工作车.
   */
  public static final String CAR_V4 =
      "api/simplecarpool/v4/findWorkCarById/{workCarId}.json?appKey={appKey}";
  /**
   * V4查询单个服务人员预约的工作车订单.
   */
  public static final String BOOKS_V4 =
      "api/simplecarpool/v4/books/{employId}.json?appKey={appKey}";
  /**
   * V4销单.
   */
  public static final String CANCEL_V4 = "api/simplecarpool/v4/cancel/{bookId}?appKey={appKey}";

  /**
   * 根据经纬度查询路线.
   */
  public Map<String, Object> roadLines(Double lng, Double lat, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("lng", String.valueOf(lng));
    kv.put("lat", String.valueOf(lat));
    kv.put("appKey", appKey);
    String result = restTemplate.getForObject(buildApi(ROADLINES), String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", code);
    String message = jo.getString("message");
    map.put("msg", message);
    if (code == 0) {
      List<WorkCarArea> list = new ArrayList<WorkCarArea>();
      JSONArray jsonArray = jo.getJSONArray("data");
      list = JSON.parseArray(jsonArray.toString(), WorkCarArea.class);
      map.put("data", list);
    }

    return map;
  }

  /**
   * 工作车下单.
   */
  
  public Map<String, Object> book(Long roadLineId, Double bookLat, Double bookLng, Long bookTime,
      String bookArea, Long employId, String employName, String employPhone, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("roadLineId", String.valueOf(roadLineId));
    kv.put("bookLat", String.valueOf(bookLat));
    kv.put("bookLng", String.valueOf(bookLng));
    kv.put("bookTime", String.valueOf(bookTime));
    kv.put("bookArea", bookArea);
    kv.put("employId", String.valueOf(employId));
    kv.put("employName", employName);
    kv.put("employPhone", employPhone);
    kv.put("appKey", appKey);

    String result = restTemplate.postForObject(buildApi(BOOK), null, String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    String message = jo.getString("message");
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("msg", message);
    map.put("code", code);
    if (code == 0) {
      JSONObject data = jo.getJSONObject("data");
      
      Map<String, Object> workCarDriver = new HashMap<String, Object>();
      Long id = data.getLong("id");
      workCarDriver.put("id", id);
      JSONArray workCarDrivers = data.getJSONArray("workCarDrivers");
      if (workCarDrivers != null) {
        List<Long> list = JSON.parseArray(workCarDrivers.toString(), Long.class);
        workCarDriver.put("workCarDrivers", list);
      }

      map.put("data", workCarDriver);
    }
    return map;
  }

  /**
   * 查询指定线路.
   */
  public Map<String, Object> roadLine(Long roadLineId, String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();

    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(ROADLINE);
    url = url.replaceAll("\\{roadLineId\\}", String.valueOf(roadLineId));
    kv.put("appKey", appKey);
    String result = restTemplate.getForObject(url, String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    String message = jo.getString("message");
    map.put("msg", message);

    map.put("code", code);
    if (code == 0) {
      JSONObject data = jo.getJSONObject("data");
      WorkCarArea workCarArea = JSON.parseObject(data.toString(), WorkCarArea.class);
      map.put("data", workCarArea);
    }
    return map;
  }

  /**
   * 更新工作车位置.
   * @param workcarId 工作车Id
   * @param address 工作车当前位置
   * @param lat 纬度
   * @param lng 经度
   */
  
  public Map<String, Object> workcar(
      Long workcarId, String address, Double lat, Double lng, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(UPDATECAR);
    url = url.replaceAll("\\{workCarId\\}", String.valueOf(workcarId));
    kv.put("appKey", appKey);
    kv.put("address", address);
    kv.put("lat", String.valueOf(lat));
    kv.put("lng", String.valueOf(lng));
    String result = restTemplate.postForObject(url, null, String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    String message = jo.getString("message");
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("msg", message);
    map.put("code", code);
    map.put("data", null);
    return map;
  }

  /**
   * 查询单个工作车.
   */
  
  public Map<String, Object> car(Long carId, String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();

    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(CAR);
    url = url.replaceAll("\\{workCarId\\}", String.valueOf(carId));
    kv.put("appKey", appKey);
    String result = restTemplate.getForObject(url, String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    String message = jo.getString("message");
    map.put("msg", message);
    map.put("code", code);
    if (code == 0) {
      JSONObject data = jo.getJSONObject("data");
      if (data != null) {
        WorkCar workCar = JSON.parseObject(data.toString(), WorkCar.class);
        if (workCar != null) {
          Long employId = workCar.getCurrentDriverId();
          if (null != employId && employId != 0) {
            map.put("data", employId);
          }
        }
      }
    }
    return map;
  }

  /**
   * 查询订单.
   */
  
  public Map<String, Object> books(Long employId, String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();

    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(BOOKS);
    url = url.replaceAll("\\{employId\\}", String.valueOf(employId));
    kv.put("appKey", appKey);
    String result = restTemplate.getForObject(url, String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    String message = jo.getString("message");
    map.put("msg", message);
    map.put("code", code);
    if (code == 0) {
      JSONObject data = jo.getJSONObject("data");
      Long bookId = data.getLong("bookId");
      Long bookTime = data.getLong("bookTime");
      String area = data.getString("area");
      String carNumber = data.getString("carNumber");
      String pikerName = data.getString("pikerName");
      String pikerPhone = data.getString("pikerPhone");
      Map<String, Object> book = new HashMap<String, Object>();
      book.put("bookTime", bookTime);
      WorkCarArea workCarArea = JSON.parseObject(area, WorkCarArea.class);
      book.put("workCarArea", workCarArea);
      book.put("carNumber", carNumber);
      book.put("pikerName", pikerName);
      book.put("pikerPhone", pikerPhone);
      book.put("bookId", bookId);
      map.put("data", book);
    }
    return map;
  }

  /**
   * 销单.
   */
  
  public Map<String, Object> cancel(Long bookId, String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();

    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(CANCEL);
    url = url.replaceAll("\\{bookId\\}", String.valueOf(bookId));
    kv.put("appKey", appKey);

    String result = restTemplate.postForObject(url, null, String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    String message = jo.getString("message");
    map.put("msg", message);
    map.put("code", code);
    Map<String, Object> data = new HashMap<String, Object>();
    JSONObject jsonObject = jo.getJSONObject("data");
    String employName = jsonObject.getString("employName");
    JSONArray jsonArray = jsonObject.getJSONArray("drivers");
    List<Long> drivers = JSON.parseArray(jsonArray.toString(), Long.class);
    data.put("drivers", drivers);
    data.put("employName", employName);
    map.put("data", data);
    return map;
  }
  
  /**
   * 创建工作车订单.
   */
  
  public ResultTransport bookV4(Long roadLineId, Double bookLat, Double bookLng, Long bookTime,
      String bookArea, Long employId, String employName, String employPhone, String appKey) {
    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
    kv.add("roadLineId", String.valueOf(roadLineId));
    kv.add("bookLat", String.valueOf(bookLat));
    kv.add("bookLng", String.valueOf(bookLng));
    kv.add("bookTime", String.valueOf(bookTime));
    kv.add("bookArea", bookArea);
    kv.add("employId", String.valueOf(employId));
    kv.add("employName", employName);
    kv.add("employPhone", employPhone);
    kv.add("appKey", appKey);

    String result = postMultiValueMap(buildApi(BOOK_V4), kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }
  
  /**
   * 根据经纬度查询路线V4.
   */
  
  public ResultTransport roadLinesV4(Double lat, Double lng, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();

    kv.put("lat", String.valueOf(lat));
    kv.put("lng", String.valueOf(lng));
    kv.put("appKey", appKey);

    String result = restTemplate.getForObject(buildApi(ROADLINES_V4), String.class, kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }
  
  /**
   * 查询单条路线V4.
   */
  
  public ResultTransport roadLineV4(Long roadLineId, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();

    kv.put("roadLineId", String.valueOf(roadLineId));
    kv.put("appKey", appKey);

    String result = restTemplate.getForObject(buildApi(ROADLINE_V4), String.class, kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }
  
  /**
   * 查询工作车.
   */
  
  public ResultTransport carV4(Long carId, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(CAR_V4);
    url = url.replaceAll("\\{workCarId\\}", String.valueOf(carId));
    kv.put("appKey", appKey);
    String result = restTemplate.getForObject(url, String.class, kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }
  
  /**
   * V4查询单个服务人员预约的工作车订单.
   */
  
  public ResultTransport booksV4(Long employId, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(BOOKS_V4);
    url = url.replaceAll("\\{employId\\}", String.valueOf(employId));
    kv.put("appKey", appKey);
    String result = restTemplate.getForObject(url, String.class, kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }
  
  /**
   * 销单V4.
   */
  
  public ResultTransport cancelV4(Long bookId, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(CANCEL_V4);
    url = url.replaceAll("\\{bookId\\}", String.valueOf(bookId));
    kv.put("appKey", appKey);

    String result = restTemplate.postForObject(url, null, String.class, kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }

  public String postMultiValueMap(String url, MultiValueMap<String, String> kv) {
    return restTemplate.postForObject(url, kv, String.class);
  }

  private String buildApi(String api) {

    StringBuilder builder = new StringBuilder();
    builder.append(simpleCarPoolApiGateway);
    if (!simpleCarPoolApiGateway.endsWith("/")) {
      builder.append("/");
    }
    builder.append(api);

    return builder.toString();
  }

}
